package com.xmg.mgrsite.filter;


import com.xmg.p2p.base.util.BidConst;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

public class SyncImgFilter implements Filter {
    private ServletContext servletContext;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.servletContext = filterConfig.getServletContext();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String file = req.getRequestURI();
        String localPath = servletContext.getRealPath(file);
        File localFile = new File(localPath);
        if (localFile.exists()) {
            chain.doFilter(request, response);
        } else {
            File publicFile = new File(BidConst.PUBLIC_IMG_SHARE_PATH, FilenameUtils.getName(file));
            if (publicFile.exists()) {
                FileUtils.copyFile(publicFile, localFile);
// 再放行;
                res.setHeader("Cache-Control", "no-store");
                res.setHeader("Pragma", "no-cache");
                res.setDateHeader("Expires", 0);
                ServletOutputStream responseOutputStream = response
                        .getOutputStream();
                responseOutputStream.write(FileUtils
                        .readFileToByteArray(publicFile));
                responseOutputStream.flush();
                responseOutputStream.close();
            }
        }
    }

    @Override
    public void destroy() {

    }
}
